﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using DuelQuizz.contract;
using DuelQuizz.DuelQuizzServiceReference;
using DuelQuizzServer;

namespace DuelQuizz
{
    /// <summary>
    /// Logique d'interaction pour Quiz.xaml
    /// </summary>
    public partial class Quiz : UserControl
    {
        List<Question> questions;
        List<Answer> answers;
        int actualQuestion;
        int questionsCount;
        User user;

        public Quiz(Category c, int questionsCount, User user)
        {
            InitializeComponent();

            questions = new List<Question>();
            answers = new List<Answer>();
            this.questionsCount = questionsCount;
            this.user = user;

            actualQuestion = -1;
            GetQuestions(c);
            NextQuestion();
        }

        private void GetQuestions(Category c)
        {
            // Call web service
            questions = AppServices.getDuelQuizzServices().getQuestionsFromCategory(c.id, this.questionsCount).ToList<Question>();
        }

        private void NextQuestion()
        {
            if (actualQuestion == questions.Count() - 1 && actualQuestion != -1)
            {
                sendAnswer.IsEnabled = false;
                int rightAnswersNumber = GetRightAnswersNumber();

                SendRightAnswersNumber();
                return;
            }

            actualQuestion = actualQuestion + 1;

            questionControl.SetQuestion(questions.ElementAt(actualQuestion));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Call web service to save answer
            answers.Add(questionControl.SelectedAnswer);
            NextQuestion();
        }

        public List<Answer> GetAnswers()
        {
            // Call web service
            return answers;
        }

        public int GetRightAnswersNumber()
        {
            int right = 0;
            // Call web service
            foreach (Answer a in answers)
                if (a.right)
                    right++;

            return right;
        }

        private void SendRightAnswersNumber()
        {
            AppServices.getDuelQuizzServices().saveResult(user.id, user.id, GetRightAnswersNumber());
        }
    }
}
